import { defineStore } from 'pinia'
import { ref } from 'vue'
import storage from '@/utils/storage'
import request from '@/utils/request'
import router from '@/router'

// 本地缓存
const data = storage.info()

export const useUserStore = defineStore('user', () => {
  // 标识
  const token = ref<string>(data.token || '')

  // 设置标识
  function setToken(data: {
    token: string
    expire: number
    refreshToken: string
    refreshExpire: number
  }) {
    token.value = data.token
    storage.set('token', data.token, data.expire)
    storage.set('refreshToken', data.refreshToken, data.refreshExpire)
  }

  // 刷新标识
  function refreshToken() {
    return new Promise((resolve, reject) => {
      request
        .get<any>('/admin/base/open/refreshToken', {
          refreshToken: storage.get('refreshToken')
        })
        .then((res) => {
          setToken(res)
          resolve(res.token)
        })
        .catch((err) => {
          logout()
          reject(err)
        })
    })
  }

  // 用户信息
  const info = ref(data.info)

  // 设置用户信息
  function set(value: any) {
    info.value = value
    storage.set('info', value)
  }

  // 获取用户信息
  async function get() {
    return request.get('/admin/base/comm/person').then((res) => {
      set(res)
      return res
    })
  }

  // 清除用户
  function clear() {
    storage.remove('info')
    storage.remove('token')
    token.value = ''
    info.value = null
  }

  // 退出
  async function logout() {
    clear()
    // router.clear()
    await router.push('/login')
  }

  return {
    token,
    info,
    get,
    set,
    logout,
    clear,
    setToken,
    refreshToken
  }
})
